(function($){
	var constants = new Object();
	constants.render = function (jq){
		var node = jq.children("div.node");
		/* render text */
		node.children("a").bind("click",function(event){
			constants.edit($(this).parent().attr("constTypeId"));
		});
		/* render toolbar*/
		var btns = $("#toolbar a");
		// refresj button;
		$(btns[0]).unbind("click");
		$(btns[0]).bind("click",function(){
			constants.refresh();
		});
		// new button;
		$(btns[1]).unbind("click");
		$(btns[1]).bind("click",function(){
			constants.edit(0);
		});
	}

	constants.edit = function(id){
		var arena = $("#arena");
		arena.empty();
		arena.load(ROOT + "/logined/const/edit.do" ,{id:id},function(){
			constants.setupEditor();
		});
	}
	
	constants.setupEditor = function(){
		var arena = $("#arena");
		//for new const value
		$("#addConst").bind("click",function(){
			$("#consts table").append('<tr><td><input name="constValue" class="const" type="text"/></td><td><a class="deleteConst" href="javascript:void(0)"><img class="icon16" src="'+ROOT+'/images/del.gif"></a></td></tr>');
			$("#consts .deleteConst").unbind("click");
			$("#consts .deleteConst").bind("click",function(){
				$(this).parent().parent().remove();
			})		
		})
		//for const value delete
		$("#consts .deleteConst").bind("click",function(){
			$(this).parent().parent().remove();
		})		
		// for delete
		$("#deleteGroup").bind("click",function(){
			var input = $("#arena input:hidden");
			if ("0" != input.val()) {
				arena.load(ROOT + "/logined/const/del.do", {
					id: input.val()
				}, function(){
					constants.refreshChute();
				});
			}
		})
		// for save
		$("#saveGroup").bind("click",function(){
			var inputs = $("#group input");
			var d = new Object();
			for(var i=0;i<inputs.length;i++){
				d[inputs[i].name] = inputs[i].value;
			}
			d["constValue"]=new Array();
			var trs = $("#consts tr");
			for(var i=0;i<trs.length;i++){
				var consInputs = $("input", trs[i]);
				for(var j=0;j<consInputs.length;j++){
					d[consInputs[j].name].push(consInputs[j].value);
				}
			}
			arena.empty();
			arena.load(ROOT + "/logined/const/save.do",d,function(){
				constants.setupEditor();
				constants.refreshChute();
			});
		})
	}
	
	constants.refreshChute = function(){
		$("#chute").load(ROOT + "logined/const/list.do", null, function(){
			constants.render($("#chute"));
		})
	}

	constants.refresh = function (){
		$("#chute").empty();
		$("#arena").empty();
		constants.refreshChute();
	}	

	// Install to jQuery
	$.constants = constants;

	/* main method */
	$(document).ready(function(){
		$.constants.refresh();	
	})
})(jQuery);
